/**
 * Description:一些注释<br/>
 * CreateTime:2019-04-06<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
package cn.cnsy123.bookwebsiteserver.service.dict.impl;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.cnsy123.bookwebsiteserver.entity.SysParamInfo;
import cn.cnsy123.bookwebsiteserver.param.DictInsertParam;
import cn.cnsy123.bookwebsiteserver.param.DictUpdateParam;
import cn.cnsy123.bookwebsiteserver.repository.DictInfoDao;
import cn.cnsy123.bookwebsiteserver.service.dict.DictInfoService;
import cn.cnsy123.bookwebsiteserver.util.JsonUtil;
import cn.cnsy123.bookwebsiteserver.vo.layui.CommonResult;
import cn.cnsy123.bookwebsiteserver.vo.layui.TableResult;

/**
 * Description:一些注释<br/>
 * CreateTime:2019-04-06<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
@Service
public class DictInfoServiceImpl implements DictInfoService {
    
    private static final Logger logger = LoggerFactory.getLogger(DictInfoServiceImpl.class);
    
    @Autowired
    private DictInfoDao dictInfoDao;

    @Override
    @Transactional(rollbackFor = RuntimeException.class,readOnly = true)
    public TableResult<SysParamInfo> findAllDictConfigInfo(int page, int size,String dictType) {
        List<SysParamInfo> data = null;
        Page<SysParamInfo> pageData = null;
        String msg = "获取数据为空,请手动配置信息";
        int flag = 1;
        long count = 0L;
        try {
            if(StringUtils.isNotBlank(dictType)) {
                pageData = dictInfoDao.findAllByDictType(dictType, PageRequest.of(page-1, size));
            }else {
                pageData = dictInfoDao.findAll(PageRequest.of(page-1, size, new Sort(Direction.ASC, "dictType")));
            }
            if(pageData != null) {
                data = pageData.getContent();
                count = pageData.getTotalElements();
                if(count > 0) {
                   msg = "获取数据成功";
                   flag = 0;
                }
            }
            
        } catch (Exception e) {
            logger.error("获取字典信息失败，原因：",e);
            msg = "获取数据出错,请通知您的系统管理员！";
            flag = 1;
            count = 0L;
            data = null;
            throw new RuntimeException("获取字典信息失败");
        }
        TableResult<SysParamInfo> result = new TableResult<SysParamInfo>(flag, msg, count, data);
        logger.info("字典配置中心查询结果:{}",JsonUtil.obj2jsonStr(result));
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public CommonResult<Object> deleteDictItemInfo(Long dictId) {
        int code = 1;
        String msg = "";
        try {
            dictInfoDao.deleteById(dictId);
            code = 0;
            msg = "删除字典项成功";
        } catch (Exception e) {
            code = 1;
            msg = "删除字典项出现异常";
            logger.error("删除字典项[id="+dictId+"]失败,原因:",e);
            throw new RuntimeException("删除字典项[id="+dictId+"]失败");
        }
        CommonResult<Object> result = new CommonResult<Object>(code, msg);
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public CommonResult<Object> updateDictItemInfo(DictUpdateParam param) {
        int code = 1;
        String msg = "";
        try {
            Optional<SysParamInfo> optional = dictInfoDao.findById(param.getDictId());
            if(optional != null) {
                SysParamInfo sysParamInfo = optional.get();
                if(sysParamInfo == null) {
                    code = 1;
                    msg = "更新字典项不存在";
                }else {
                    sysParamInfo.setDictType(param.getDictType());
                    sysParamInfo.setDictCode(param.getDictCode());
                    sysParamInfo.setDictDesc(param.getDictDesc());
                    dictInfoDao.save(sysParamInfo);
                    code = 0;
                    msg = "更新字典项成功";
                }
            }
        } catch (Exception e) {
            code = 1;
            msg = "更新字典项出现异常";
            logger.error("更新字典项[id="+param.getDictId()+"]失败,原因:",e);
            throw new RuntimeException("更新字典项[id="+param.getDictId()+"]失败");
        }
        CommonResult<Object> result = new CommonResult<Object>(code, msg);
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public CommonResult<Object> insertDictItemInfo(DictInsertParam param) {
        int code = 1;
        String msg = "";
        try {
                SysParamInfo sysParamInfo = new SysParamInfo();
                sysParamInfo.setDictCode(param.getDictCode());
                sysParamInfo.setDictDesc(param.getDictDesc());
                sysParamInfo.setCreateTime(new Date());
                sysParamInfo.setDictType(param.getDictType());
                dictInfoDao.save(sysParamInfo);
                code = 0;
                msg = "新增字典项成功";
        } catch (Exception e) {
            code = 1;
            msg = "新增字典项出现异常";
            logger.error("新增字典项[dictType="+param.getDictType()+",dictCode="+param.getDictCode()+"]失败,原因:",e);
            throw new RuntimeException("新增字典项[dictType="+param.getDictType()+",dictCode="+param.getDictCode()+"]失败");
        }
        CommonResult<Object> result = new CommonResult<Object>(code, msg);
        return result;
    }

}
